package com.mindskip.gushuang.utility;


import com.mindskip.gushuang.configuration.property.PhotosConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ResourceUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;


@Component
public class UpPhotoNameUtils {
    @Autowired
    PhotosConfig photosConfig;

    static String UserPicRoot = "static/";

    public String SaveUserPic(String LodPath, MultipartFile file, Long menuId) {
        String contentType = file.getContentType();
        if (!photosConfig.getAllowTypes().contains(contentType)) {
            return null;
        }
        try {
            UserPicRoot = ResourceUtils.getURL("classpath:").getPath() + "static/";
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        String savePath = UserPicRoot + LodPath;
        String realsavePath = savePath.replace('/', '\\').substring(1, savePath.length());
        File dirFile = new File(realsavePath);
        boolean bFile = dirFile.exists();
        if (!bFile) {
            dirFile.mkdirs();
        }
        String resultName = "/image/" + menuId + "." + contentType.split("/")[1];
        savePath = savePath + "/" + menuId + "." + contentType.split("/")[1];
        try {
            file.transferTo(new File(savePath));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return resultName;
    }
}
